package com.itdaan.portal.business.controller;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.itdaan.portal.business.controller.ShiroDbRealm.ShiroUser;
import com.itdaan.portal.business.domain.Comment;
import com.itdaan.portal.business.domain.Page;
import com.itdaan.portal.business.service.CommentService;
import com.itdaan.portal.business.service.WebTypeService;
import com.itdaan.portal.common.exception.ServiceException;
import com.itdaan.portal.common.exception.ViewException;

/**
 * 评论业务控制类 
 * @author www.itdaan.com
 * @Deprecated 此类已过期，评论交由社会化控件
 */
@Controller
@RequestMapping(value = "/user/comment")
@SessionAttributes
@Deprecated
public class CommentController {

	private Logger logger = LoggerFactory.getLogger(CommentController.class);
	
	@Resource(name = "commentService")
	private CommentService commentService;
	@Resource(name = "webTypeService")
	private WebTypeService webTypeService;	
	
	@RequiresPermissions("comment:save")//有权限的登陆用户都可以评论
	@RequestMapping(value = "/save", method = {RequestMethod.POST})
    public
    @ResponseBody
    Map<String,Object> save(
            HttpServletRequest request,
            HttpServletResponse response,
            @RequestParam(value = "id", required = false) Integer id,
            @RequestParam(value = "comment", required = true) String comment
    		) throws ViewException {
		Map<String, Object> modelAndView = new HashMap<String, Object>();
        try{
    		String referer = request.getHeader("referer");
    		if(StringUtils.isEmpty(referer) || referer.indexOf(id.toString()) == -1 ){//来路我某个帖子时才更新
    			modelAndView.put("success", "false");
    			return modelAndView;
    		}        		
   			Subject currentUser = SecurityUtils.getSubject();
			if(currentUser.isRemembered() || currentUser.isAuthenticated()){//记住的用户
				ShiroUser shiroUser = (ShiroUser)currentUser.getPrincipals().getPrimaryPrincipal();
				Comment postComment = new Comment();
				postComment.setPostId(id);
				postComment.setComment(comment);
				postComment.setUserId(shiroUser.getId());
				postComment.setName(shiroUser.getName());
				postComment.setAvatar(shiroUser.getAvatar());
				commentService.insertComment(postComment);
				modelAndView.put("success", "true");//返回success为true
				modelAndView.put("login", true);
			}else{
				modelAndView.put("success", "false");
				modelAndView.put("login", false);
			}
        }catch(Exception e){
			logger.error("后台业务逻辑出现异常", e);
			modelAndView.put("success", "false");
    	}
		return modelAndView;
	}
	
	@RequiresPermissions("comment:edit")//控制只有 有admin权限的才能执行该方法
	@RequestMapping(value = "/edit", method = {RequestMethod.POST})
    public
    @ResponseBody
    Map<String,Object> edit(
            HttpServletRequest request,
            HttpServletResponse response,
            @RequestParam(value = "id", required = false) Integer id,
            @RequestParam(value = "comment", required = true) String comment
    		) throws ViewException {
		Map<String, Object> modelAndView = new HashMap<String, Object>();
        try{
			Comment postComment = new Comment();
			postComment.setId(id);
			postComment.setComment(comment);
			commentService.updateComment(postComment);
			modelAndView.put("success", "true");
        }catch(Exception e){
			logger.error("后台业务逻辑出现异常", e);
			modelAndView.put("success", "false");
    	}
		return modelAndView;
	}
	
	@RequiresPermissions("comment:audit")//有审核权限的 登陆用户可以审核
	@RequestMapping(value = "/audit", method = {RequestMethod.GET,RequestMethod.POST})
    public
    String audit(
            HttpServletRequest request,
            HttpServletResponse response,
            @RequestParam(value = "ids", required = false) String ids,
            @RequestParam(value = "id", required = false) Integer id,
            @RequestParam(value = "audit", required = false) Integer audit,
            @RequestParam(value = "auditContent", required = false) String auditContent
    		) throws ViewException {
        try{
        	if(!StringUtils.isEmpty(ids)){
            	Subject currentUser = SecurityUtils.getSubject();
            	ShiroUser shiroUser = (ShiroUser)currentUser.getPrincipals().getPrimaryPrincipal();
        		for (String idstr : ids.split(",")) {
        			Comment postComment = new Comment();
        			postComment.setId(Integer.parseInt(idstr));
        			postComment.setAudit(audit);
        			postComment.setAuditUserId(shiroUser.getId());
        			postComment.setAuditName(shiroUser.getName());
        			postComment.setAuditContent(auditContent);
        			commentService.updateComment(postComment);
        		}
        	}else if(id != null){
            	Subject currentUser = SecurityUtils.getSubject();
            	ShiroUser shiroUser = (ShiroUser)currentUser.getPrincipals().getPrimaryPrincipal();
    			Comment postComment = new Comment();
    			postComment.setId(id);
    			postComment.setAudit(audit);
    			postComment.setAuditUserId(shiroUser.getId());
    			postComment.setAuditName(shiroUser.getName());
    			postComment.setAuditContent(auditContent);
    			commentService.updateComment(postComment);
        	}
        }catch(Exception e){
			logger.error("后台业务逻辑出现异常", e);
    	}
        String referer = request.getHeader("referer");
        if(StringUtils.isEmpty(auditContent)){
        	return "redirect:"+referer;
        }else{
        	return null;
        }
	}
	
	@RequestMapping(value = "/list", method = {RequestMethod.GET})
	public String list(
			@RequestParam(value = "postId", required = false) Integer postId,
			@RequestParam(value = "page", defaultValue = "1") int current,
			Model model) {
		Map<String, Object> conditions = new HashMap<String, Object>();
		Subject currentUser = SecurityUtils.getSubject();
		if(currentUser.isRemembered() || currentUser.isAuthenticated()){//记录的登陆用户
			ShiroUser shiroUser = (ShiroUser)currentUser.getPrincipals().getPrimaryPrincipal();
			conditions.put("userId", shiroUser.getId());
		}else{
			return "403";
		}
		conditions.put("postId", postId);
		Page page = new Page();
		page.setConditions(conditions);
		page.setCurrent(current);
		try {
			commentService.findByPage(page);
		} catch (ServiceException e) {
			logger.error("查询评论信息失败：{}",e.toString());
		}
		model.addAttribute("page", page);

		return "user/comment_list";
	}
	
	@RequestMapping(value = "/listall", method = {RequestMethod.GET})
	public String listall(
			@RequestParam(value = "postId", required = false) Integer postId,
			@RequestParam(value = "page", defaultValue = "1") Integer current,
			@RequestParam(value = "audit") Integer audit,
			Model model) {
		Map<String, Object> conditions = new HashMap<String, Object>();
		Subject currentUser = SecurityUtils.getSubject();
		if(currentUser.isRemembered() || currentUser.isAuthenticated()){//记录的登陆用户
			if(!currentUser.hasRole("admin") && !currentUser.hasRole("publisher")){
				return "403";
			}
		}else{
			return "403";
		}
		conditions.put("postId", postId);
		conditions.put("audit", audit);
		Page page = new Page();
		page.setConditions(conditions);
		page.setCurrent(current);
		try {
			commentService.findByPage(page);
		} catch (ServiceException e) {
			logger.error("查询评论信息失败：{}",e.toString());
		}
		model.addAttribute("page", page);

		return "user/comment_list";
	}	
}
